const router = require('koa-router')()
const DB = require('../../utils/db.js')

router.get('/add/:id/:bid', async (ctx) => {
  // http://localhost:3000/add/112/qwe
  console.log(ctx.params)
  // { id: '112', bid: 'qwe' }
  ctx.body = '添加详情'
})

// 查询
router.get('/list', async (ctx) => {
  const result = await DB.find('user', {})
  ctx.body = result
})

// 插入
router.post('/doAdd', async (ctx) => {
  let data = await DB.insert('user', ctx.request.body)
  ctx.body = data
  try {
    if (data.result.ok) {
      ctx.body = data
    }
  } catch (error) {
    ctx.redirect('/')
  }
})

// 删除
router.get('/remove', async (ctx) => {
  let user = ctx.request.body.user
  const data = await DB.remove('user', { 'user': user })
  try {
    if (data.result.ok) {
      ctx.body = data
    }
  } catch (error) {
    console.log(err)
  }
})

// 更新
router.get('/update', async (ctx) => {
  const id = ctx.query.id
  const user = ctx.query.user
  const age = ctx.query.age
  const sex = ctx.query.sex

  let data = await DB.update('user', { '_id': DB.getObjectID(id) }, {
    age,
    sex
  })

  try {
    if (data.result.ok) {
      ctx.body = data
    }
  } catch (error) {
    console.log(err)
    ctx.redirect('/add')
  }
})


module.exports = router
